<template>
  <a-modal
    class="formModal"
    :title="$t('form.updateMobile.title')"
    v-model:open="modalVisible"
    @cancel="close"
    :footer="null"
  >
    <a-form ref="formRef" :model="formState">
      <template v-if="memberStore.profile?.mobile">
        <a-form-item
          :label="$t('form.updateMobile.form.item_1.label')"
          name="oldmobile"
          :rules="[{ validator: checkOldMobile, trigger: 'blur' }]"
        >
          <a-input
            v-model:value.trim="formState.oldmobile"
            :maxlength="30"
            :placeholder="$t('form.updateMobile.form.item_1.rules.error_1')"
            allowClear
          ></a-input>
        </a-form-item>
      </template>
      <a-form-item
        :label="$t('form.updateMobile.form.item_2.label')"
        name="mobile"
        :rules="[{ validator: checkNewMobile, trigger: 'blur' }]"
      >
        <a-input
        
            :maxlength="30"
          v-model:value.trim="formState.mobile"
          :placeholder="$t('form.updateMobile.form.item_2.rules.error_1')"
          allowClear
        ></a-input>
      </a-form-item>
      <a-form-item
        :label="$t('form.code.label')"
        name="captcha"
        :rules="[{ validator: checkCaptcha, trigger: 'blur' }]"
      >
        <div class="get-code-item">
          <a-input
            :maxlength="6"
            v-model:value.trim="formState.captcha"
            :placeholder="$t('form.code.placeholder')"
            allowClear
          ></a-input>
          <a-button class="getCode" @click="getCode" v-if="!tempCode">{{
            $t("form.code.get_code")
          }}</a-button>
          <tepmlate v-else>
            <a-button class="getCode" @click="getCode" v-if="!getCoding">{{
              $t("form.code.re_get_code")
            }}</a-button>
            <a-button class="getCode getCoding" v-else
              >{{ codeNumber }}s</a-button
            >
          </tepmlate>
        </div>
      </a-form-item>
    </a-form>
    <div class="footer-btns">
      <a-button @click="close">{{ $t("btnText.cancel") }}</a-button>
      <a-button type="primary" :loading="isSubmitting" @click="submit">{{
        $t("btnText.ensure")
      }}</a-button>
    </div>
  </a-modal>
</template>

<script setup lang="ts">
import { getCurrentInstance, ref } from "vue";
import type { UpdateMobileParams } from "../../../types/member";
import { useMemberStore } from "../../../store";
import { message } from "ant-design-vue";
import { postUpdateMobile } from "../../../api/member";
import { postSendPhoneCode } from "../../../api/api";
import { RegMobile } from "../../../data/reg";

const $t = getCurrentInstance()?.appContext.config.globalProperties.$t;

const memberStore = useMemberStore();
const modalVisible = ref(false);
const close = () => {
  modalVisible.value = false;
  formRef.value.resetFields();
};

const show = () => {
  modalVisible.value = true;
};

defineExpose({
  close,
  show,
});

// ===============form state================
const formRef = ref();

const formState = ref<UpdateMobileParams & { oldmobile?: string }>({
  oldmobile: "",
  mobile: "",
  captcha: "",
});

const checkOldMobile = (_Rule: any, value: string) => {
  if (!memberStore.profile?.mobile) return Promise.resolve();
  if (!value) {
    return Promise.reject($t("form.updateMobile.form.item_1.rules.error_1"));
  }
  if (!RegMobile.test(value)) {
    return Promise.reject($t("reg_rules.mobile"));
  }
  if (value !== memberStore.profile?.mobile) {
    return Promise.reject($t("form.updateMobile.no_match"));
  } else {
    return Promise.resolve();
  }
};

const mobileIsValid = ref(false);
const checkNewMobile = (_Rule: any, value: string) => {
  if (!value) {
    mobileIsValid.value = false;
    return Promise.reject($t("form.updateMobile.form.item_2.rules.error_1"));
  }
  if (!RegMobile.test(value)) {
    mobileIsValid.value = false;
    return Promise.reject($t("reg_rules.mobile"));
  } else {
    mobileIsValid.value = true;
    return Promise.resolve();
  }
};

const tempCode = ref("");
let getCoding = ref(false);
let getCodeTimer: any = null;
let codeNumber = ref(60);
const getCode = async () => {
  if (!mobileIsValid.value) return message.error($t("reg_rules.mobile"));
  if (getCodeTimer) return;
  let res = await postSendPhoneCode({
    mobile: formState.value.mobile,
    type: "update_mobile",
  });
  if (res.code === 200) {
    message.success(res.msg);
    getCoding.value = true;
    tempCode.value = res.captcha!;
    getCodeTimer = setInterval(() => {
      if (codeNumber.value === 0) {
        clearInterval(getCodeTimer);
        getCoding.value = false;
        codeNumber.value = 60;
        getCodeTimer = null;
      }
      codeNumber.value--;
    }, 1000);
  } else {
    message.error(res.msg || res.message);
  }
};

const checkCaptcha = (_Rule: any, value: string) => {
  if (!tempCode.value) {
    return Promise.reject($t("form.code.error_1"));
  }
  if (value != tempCode.value) {
    return Promise.reject($t("form.code.error_2"));
  }
  return Promise.resolve();
};


const isSubmitting = ref(false);
const submit = () => {
  formRef.value.validate().then(async () => {
    isSubmitting.value = true;
    let res = await postUpdateMobile(formState.value);
    isSubmitting.value = false;
    if (res.code === 200) {
      message.success($t("message.changed_success"));
      memberStore.profile!.mobile = formState.value.mobile;
      close();
    } else {
      message.error($t('message.error.update'));
    }
  });
};
</script>
<style scoped lang="less"></style>
